<template>
  <!-- 设备接入 -->
  <div class="filterContent">
    <a-form :model="filterForm" layout="inline">
      <a-form-item label="电站名称">
        <a-input
          v-model:value="filterForm.stationName"
          class="formInput"
          placeholder="请输入"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="项目名称">
        <a-input
          v-model:value="filterForm.projectName"
          class="formInput"
          placeholder="请输入"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="所属厂商">
        <a-select
          v-model:value="filterForm.supplierId"
          class="formInput"
          placeholder="请选择"
          allow-clear
        >
          <a-select-option
            v-for="item in supplierList"
            :value="item.supplierId"
            :key="item.supplierId"
            :title="item.supplierShortName"
          >
            {{ item.supplierShortName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="是否高压项目">
        <a-select
          ref="select"
          v-model:value="filterForm.isHighVoltage"
          class="formInput"
          allow-clear
          placeholder="请选择"
        >
          <a-select-option :value="1">是</a-select-option>
          <a-select-option :value="0">否</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="电站状态">
        <a-select
          ref="select"
          v-model:value="filterForm.es"
          class="formInput"
          allow-clear
          placeholder="请选择"
        >
          <a-select-option
            v-for="item in ENERGY_STATION_STATUS"
            :value="item.value"
            :key="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-button type="primary" class="filterBtn" @click="handleFilter"
        >查询</a-button
      >
      <a-button
        type="primary"
        class="filterBtn greenBtn"
        @click="handleAddStation"
        v-hasPermission="'equipAccessAdd'"
        >新增电站</a-button
      >
      <a-button
        v-hasPermission="'equipAccessExport'"
        key="submit"
        type="primary"
        :loading="loading"
        class="yellowBtn"
        @click="handleExport"
        >导出</a-button
      >
    </a-form>
  </div>
  <div class="tableContent">
    <a-table
      :dataSource="tableData"
      :columns="columns"
      size="small"
      :scroll="{ x: 'max-content' }"
      :pagination="false"
      @resizeColumn="handleResizeColumn"
      :loading="tableLoading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'es'">
          {{
            ENERGY_STATION_STATUS.filter((item) => item.value === record.es)[0]
              ?.label
          }}
        </template>
        <template v-if="column.key === 'isHighVoltage'">
          {{ record.isHighVoltage === 1 ? "是" : "否" }}
        </template>

        <template v-if="column.key === 'handle'">
          <a-popconfirm
            ok-text="确认"
            cancel-text="取消"
            @confirm="handleStatus(record)"
          >
            <template #title>
              {{
                `是否确定${
                  record.es === 1 || record.es === 2 || record.es === 4
                    ? "启用"
                    : "停运"
                }？`
              }}
            </template>
            <a-button v-hasPermission="'equipAccessStatus'" type="link" danger>
              {{
                record.es === 1 || record.es === 2 || record.es === 4
                  ? "启用"
                  : "停运"
              }}
            </a-button>
          </a-popconfirm>
          <a-button
            type="link"
            v-hasPermission="'equipAccessEdit'"
            @click="handleEdit(record)"
            >编辑</a-button
          >
          <a-button
            type="link"
            v-hasPermission="'equipAccessTopology'"
            @click="handleTopologyMap(record)"
            >拓扑图</a-button
          >
          <a-button
            type="link"
            @click="setVisible(record, 1)"
            :disabled="!record.wiringDiagramUrl"
            v-hasPermission="'equipAccessWiringDiagram'"
            >一次接线图</a-button
          >
          <a-button
            type="link"
            @click="setVisible(record, 2)"
            :disabled="!record.networkDiagramUrl"
            v-hasPermission="'equipAccessNetworkDiagram'"
            >组网图</a-button
          >
          <a-button
            v-hasPermission="'equipAccessProtocol'"
            type="link"
            @click="handleProtocol(record)"
            >通讯协议</a-button
          >
        </template>
      </template>
    </a-table>
    <a-pagination
      v-model:current="filterForm.current"
      v-model:page-size="filterForm.size"
      :total="total"
      position="bottomRight"
      show-size-changer
      @change="getCompanyStationtPage()"
      :show-total="(total) => `总共 ${total} 条`"
    >
      <template #buildOptionText="props">
        <span>{{ props.value }}条/页</span>
      </template>
    </a-pagination>
  </div>
  <!-- 新增电站 -->
  <AddStation
    ref="addStationRef"
    :addStationVisible="addStationVisible"
    :rowData="rowData"
    :isEdit="isEdit"
    @update:addStationVisible="(val) => (addStationVisible = val)"
    @getCompanyStationtPage="(val) => getCompanyStationtPage(val)"
  />
  <!-- 通讯协议 -->
  <CommunicationProtocol
    :protocolVisible="protocolVisible"
    :rowData="rowData"
    @update:protocolVisible="(val) => (protocolVisible = val)"
  />

  <a-image
    v-if="visible && isImageFile"
    :width="200"
    :preview="{
      visible,
      onVisibleChange: setVisible,
      src: wiringDiagramUrl,
    }"
  />
  <!-- pdf 预览 -->
  <div class="maskBox" v-if="visible && isPdfFile">
    <div class="text-right mt20" style="padding-right: 25px">
      <a-button
        type="primary"
        shape="circle"
        :size="size"
        class="previewCloseIcon"
        @click="closePreview"
      >
        <template #icon>
          <CloseOutlined />
        </template>
      </a-button>
    </div>
    <div class="wordBox">
      <div ref="container"></div>
      <iframe :src="wiringDiagramUrl" height="900px;" width="1000px"></iframe>
    </div>
  </div>
</template>
<script setup>
import AddStation from "./conpoments/AddStation/index.vue";
import CommunicationProtocol from "./conpoments/CommunicationProtocol/index.vue";
import { ENERGY_STATION_STATUS } from "@/constants/stationConfig";
import { pickBy } from "lodash-es";
import { useStionConfigStore } from "@/stores/stationConfig";
import utilsExportFile from "@/utils/exportFile";
const { changeIsEditDrag } = useStionConfigStore();
const $api = inject("$api");
const filterForm = ref({
  stationName: null,
  projectName: null,
  supplierId: null,
  isHighVoltage: null,
  es: null,
  current: 1,
  size: 10,
});
const total = ref(0);
const addStationVisible = ref(false);
const previewVisible = ref(false);
const protocolVisible = ref(false);
const rowData = ref({});
const isEdit = ref(false);
const tableData = ref([]);
const tableLoading = ref(false);
const addStationRef = ref();
const columns = ref([
  {
    title: "电站名称",
    dataIndex: "stationName",
    key: "stationName",
    width: 200,
    resizable: true,
    align: "center",
  },
  {
    title: "项目名称",
    dataIndex: "projectName",
    key: "projectName",
    width: 200,
    resizable: true,
    align: "center",
  },
  {
    title: "所属厂商",
    dataIndex: "supplierName",
    key: "supplierName",
    width: 220,
    resizable: true,
    align: "center",
  },
  {
    title: "设备型号",
    dataIndex: "equipModelName",
    key: "equipModelName",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "电站容量（MWh)",
    dataIndex: "capacity",
    key: "capacity",
    width: 140,
    resizable: true,
    align: "center",
  },
  {
    title: "是否高压项目",
    dataIndex: "isHighVoltage",
    key: "isHighVoltage",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "电站状态",
    dataIndex: "es",
    key: "es",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "投运日期",
    dataIndex: "operationDate",
    key: "operationDate",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    width: 380,
    resizable: true,
    align: "center",
    fixed: "right",
  },
]);
function handleResizeColumn(w, col) {
  col.width = w;
}
const handleAddStation = () => {
  isEdit.value = false;
  addStationVisible.value = true;
};
const visible = ref(false);
const wiringDiagramUrl = ref("");
const wiringDiagramUrlExt = ref("");
const isPdfFile = ref(false);
const isImageFile = ref(false);
const closePreview = () => {
  visible.value = false;
};

const setVisible = (value, type) => {
  visible.value = value;
  wiringDiagramUrl.value =
    type === 1 ? value.wiringDiagramUrl : value.networkDiagramUrl;
  // 获取URL的后缀名
  wiringDiagramUrlExt.value = wiringDiagramUrl.value?.split(".").pop() || "";
  // 判断文件类型是图片还是PDF
  const imageExtensions = [
    "jpg",
    "jpeg",
    "png",
    "gif",
    "bmp",
    "webp",
    "tiff",
    "raw",
  ];
  isPdfFile.value = wiringDiagramUrlExt.value.toLowerCase() === "pdf";
  isImageFile.value = imageExtensions.includes(
    wiringDiagramUrlExt.value.toLowerCase()
  );
};
const handleProtocol = (data) => {
  rowData.value = data;
  protocolVisible.value = true;
};
const getCompanyStationtPage = async (data) => {
  if (data) {
    // 如果这里有data，即是新增电站后emit上来的数据，用于给rowData赋值
    filterForm.value.current = 1;
    filterForm.value.size = 10;
    rowData.value = data;
  }
  const params = {
    ...filterForm.value,
  };
  tableLoading.value = true;
  const res = await $api.companyStationtPage(pickBy(params));
  tableLoading.value = false;
  if (res && res.code === 0) {
    tableData.value = res?.data?.records;
    total.value = res?.data?.total;
  }
};
const handleStatus = async (data) => {
  // 0-非储能企业；1-待建设；2-建设中；3-运行中；4-停运
  const params = {
    stationId: data.stationId,
    es: data.es === 3 ? 4 : 3,
    updateEs: 1, // 启/停用这里写死为1给后端，用于区分是操作的启停用还是编辑里的
  };
  const res = await $api.companyStation(params, "put");
  if (res && res.code === 0) {
    message.success("操作成功");
    getCompanyStationtPage();
  }
};
const handleEdit = (data) => {
  changeIsEditDrag(false);
  rowData.value = data;
  isEdit.value = true;
  addStationVisible.value = true;
};

const handleTopologyMap = (data) => {
  if (!data.equipModelId) {
    message.warning("请先编辑电站-选择设备型号");
    return;
  }
  changeIsEditDrag(false);
  addStationRef.value.getStationTopologyMapDetails(data.stationId);
  rowData.value = data;
  isEdit.value = true;
  addStationRef.value.changeSetp(1);
  addStationVisible.value = true;
};
const supplierList = ref([]);
const getSupplierTypeTree = async () => {
  const res = await $api.supplierTypeTree();
  supplierList.value = res.data;
};
const handleFilter = () => {
  filterForm.value.current = 1;
  filterForm.value.size = 10;
  getCompanyStationtPage();
};
const handleExport = async () => {
  const { current, size, ...rest } = filterForm.value;
  const res = await $api.companyStationExport(rest);
  // fileName格式：20250617154057 是当前时间，去除 - 空格
  const now = new Date();
  const fileName =
    "项目信息" +
    now.getFullYear() +
    String(now.getMonth() + 1).padStart(2, "0") +
    String(now.getDate()).padStart(2, "0") +
    String(now.getHours()).padStart(2, "0") +
    String(now.getMinutes()).padStart(2, "0") +
    String(now.getSeconds()).padStart(2, "0");
  utilsExportFile.exportFile(res, fileName + ".xlsx");
};
onMounted(() => {
  getSupplierTypeTree();
  getCompanyStationtPage();
});
</script>

<style lang="less" scoped>
.ant-table {
  .ant-btn {
    padding: 4px 5px;
  }
}
.formInput {
  width: 155px;
}
.filterBtn {
  margin-right: 20px;
  &:last-child {
    margin-right: 0;
  }
}
.tableContent {
  border-radius: 4px;
  background-color: #141414;
  padding: 8px;
}
.maskBox {
  position: fixed;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.6);
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  z-index: 9999;
  .wordBox {
    margin: 20px auto;
    width: 1000px;
    height: calc(100vh - 50px);
    background-color: transparent;
    overflow-y: auto;
    position: relative;
    text-align: center;
  }
  .previewImg {
    max-width: 80%;
    max-height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
.previewCloseIcon {
  width: 34px;
  height: 34px;
  font-size: 20px;
  color: #fff;
  background-color: var(--el-text-color-regular);
  border-color: #fff;
  border-radius: 50%;
  position: absolute;
  right: 20px;
  top: 20px;
  line-height: 17px;
}
.btnContent {
  margin-top: 40px;
  text-align: center;
}
</style>
